package com.ptu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.ptu.spzx.manager.service.ValidateCodeService;
import com.ptu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    //redis注入
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public ValidateCodeVo generateValidateCode() {
        //1,通过工具生成图片的验证码huthool
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String codeValue = circleCaptcha.getCode();//验证码值
        System.out.println("======");
        System.out.println(codeValue);
        System.out.println("======");
        String imageBase64 = circleCaptcha.getImageBase64();//放回图片的验证码 进行base64的编码
        //2，把验证码存储到redis里面去 设置redis的key：uuid redis的value：验证码这个值
        //设置过期时间
        String key = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set("user:validate"+key,
                                         codeValue,
                                         5,
                                         TimeUnit.MINUTES);
        //返回ValidateCodeVo对象
        ValidateCodeVo validateCodeVo=new ValidateCodeVo();
        validateCodeVo.setCodeKey(key); //redis存储数据的key
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);
        System.out.println(validateCodeVo);
        return validateCodeVo;
    }
}
